package com.tudouji.framework.task;

import com.tudouji.project.customer.domain.Customer;
import com.tudouji.project.customer.service.ICustomerService;
import com.tudouji.project.mt.domain.*;
import com.tudouji.project.mt.service.*;
import com.tudouji.project.organization.domain.Department;
import com.tudouji.project.organization.domain.Organization;
import com.tudouji.project.organization.service.IOrganizationService;
import com.tudouji.project.organization.service.ISupplierService;
import com.tudouji.project.product.domain.Salesspecification;
import com.tudouji.project.product.service.ISalesspecificationService;
import com.tudouji.project.store.domain.Stockunit;
import com.tudouji.project.store.domain.Storehouseroom;
import com.tudouji.project.store.domain.Storeroom;
import com.tudouji.project.store.service.IStockunitService;
import com.tudouji.project.store.service.IStorehouseroomService;
import com.tudouji.project.store.service.IStoreroomService;
import com.tudouji.framework.task.MeituanDataProcessUtil.ProcessWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

/**
 * 美团数据加工
 */
@Service("mtwhoutdp")
@Slf4j
public class MeituanWhoutDataProcessing {
    @Autowired
    private ISupplierService supplierService;

    @Autowired
    private IOrganizationService organizationService;

    @Autowired
    private ICustomerService customerService;

    @Autowired
    private ISalesspecificationService salesspecificationService;

    @Autowired
    private IStoreroomService storeroomService;

    @Autowired
    private IStorehouseroomService storehouseroomService;

    @Autowired
    private IStockunitService stockunitService;

    @Autowired
    private IMtShopService mtShopService;

    @Autowired
    private IMtWhinService mtWhinService;
    @Autowired
    private IMtWhinitemService mtWhinitemService;

    @Autowired
    private IMtWhoutService mtWhoutService;
    @Autowired
    private IMtWhoutitemService mtWhoutitemService;

    @Autowired
    private MeituanDataProcessUtil meituanDataProcessUtil;


    /**
     * 处理美团入库单的数据加工
     */
    public void whoutProcess(){
        log.info("=========美团出库单数据加工开始===============");
        List<MtShop> mtShopList = mtShopService.selectMtShopList(new MtShop());
        for(MtShop mtShop:mtShopList){
            if(mtShop.getStatus()==1){
                whoutProcessForShop(mtShop);
            }
        }
        log.info("=========美团出库单数据加工结束===============");

    }

    /**
     * 处理某一店铺的出库单
     * @param mtShop
     */
    public void whoutProcessForShop(MtShop mtShop){
        MtWhout lookup = new MtWhout();
        //设置查询条件，查询状态为 1 - 初始，或者状态为 10 - 资料不全的美团入库单主表数据
        //需要有时间范围，仅查询推送数据前 n 天 到当前的数据即可
        //Long startBiztime = DateUtils.addDays(mtShop.getWhinAsyndate(),-3).getTime();
        lookup.setStartBiztime(mtShop.getPushdate().getTime());
        lookup.setMtShopld(mtShop.getId());
        //lookup.setStatus(1);
        List<MtWhout> mtWhoutList = mtWhoutService.selectMtWhoutList(lookup);
        for(MtWhout mtWhout:mtWhoutList){
            if(mtWhout.getStatus()!=1 && mtWhout.getStatus()!=10){
                continue;
            }
            mtWhout.setRemark("");
            whoutProcessForWhinOrder(mtWhout,mtShop);
            //更新主表数据
            mtWhoutService.updateMtWhout(mtWhout);
        }
    }

    /**
     * 为美团出库单进行数据加工：加工一条美团出库单主表数据
     * @param mtWhout   出库单主表数据
     */
    private boolean whoutProcessForWhinOrder(MtWhout mtWhout, MtShop mtShop) {
        boolean result=true;

        //首先获取组织信息
        Organization organization = meituanDataProcessUtil.getOrgnization(mtShop);
        mtWhout.setOrgId(organization.getId());
        mtWhout.setOrgName(organization.getName());

        //设置出库单类型
        mtWhout.setErpType(meituanDataProcessUtil.getWhoutErpTypeByMtType(false, mtWhout.getType()));
        if(mtWhout.getErpType()==null){
            mtWhout.setStatus(10);
            mtWhout.setRemark("入库单类型匹配错误");
            return false;
        }

        //设置出库类型，并处理跨组织
        if(!diffOrgProcess(mtWhout,mtShop)){
            return false;
        }

        ProcessWrapper<Department> dprocessWrapper = meituanDataProcessUtil.getDepartment(mtShop);
        if(!dprocessWrapper.isSuccess()){
            mtWhout.setStatus(10);
            mtWhout.setRemark(dprocessWrapper.getMessage());
            return false;
        }
        mtWhout.setDepartmentguid(dprocessWrapper.getTarget().getGuid());
        //开始处理明细表数据
        if(whoutprocessForWhoutItems(mtWhout,mtShop)){
            mtWhout.setStatus(50);
            result =  true;
        }else{
            //明细表处理的过程中，主表状态其实已经处理过了，最终兜底
            mtWhout.setStatus(10);
            result = false;
        }
        if(mtWhout.getType().intValue()==9) {
            //菜品销售出库单，不处理 9 - 菜品销售出库
            mtWhout.setStatus(30);
        }
        return result;
    }

    /**
     * 加工美团出库单明细表数据：加工一条主表数据对应的所有明细数据
     * @param mtWhout   出库单主表
     * @param mtShop    店铺
     */
    private boolean whoutprocessForWhoutItems(MtWhout mtWhout, MtShop mtShop) {
        MtWhoutitem lookup = new MtWhoutitem();
        lookup.setMtWhoutid(mtWhout.getId());
        boolean processFlag = true;
        List<MtWhoutitem> mtWhoutitems = mtWhoutitemService.selectMtWhoutitemList(lookup);

        //没有明细数据
        if(mtWhoutitems.size()==0){
            mtWhout.setStatus(10);
            mtWhout.setRemark("没有找到明细数据");
            return false;
        }


        for(MtWhoutitem mtWhoutitem:mtWhoutitems){
            mtWhoutitem.setRemark("");
            if(!whoutProcessForWhoutItem(mtWhout,mtWhoutitem,mtShop)){
                processFlag=false;
            }
            //更新当前数据
            mtWhoutitemService.updateMtWhoutitem(mtWhoutitem);
        }
        return processFlag;
    }

    /**
     * 加工某一条美团出库单明细表数据：加工一条美团出库单明细数据
     * @param mtWhout    出库单主表数据
     * @param mtWhoutitem  出库单明细数据
     * @return
     */
    private boolean whoutProcessForWhoutItem(MtWhout mtWhout,MtWhoutitem mtWhoutitem, MtShop mtShop) {

        //处理物料信息
        ProcessWrapper<Salesspecification> spProcessWrapper = meituanDataProcessUtil.processSalesSpec(mtWhoutitem.getGoodsCode(),mtShop);
        if(!spProcessWrapper.isSuccess()){
            mtWhout.setRemark(spProcessWrapper.getMessage());
            mtWhoutitem.setRemark(spProcessWrapper.getMessage());
            mtWhout.setStatus(10);
            return false;
        }
        Salesspecification salesspecification = spProcessWrapper.getTarget();
        mtWhoutitem.setProductguid(salesspecification.getProductguid());
        mtWhoutitem.setProductname(salesspecification.getProductname());
        mtWhoutitem.setSpguid(salesspecification.getGuid());
        mtWhoutitem.setSpname(salesspecification.getName());

        //处理库房及库间
        ProcessWrapper<Storehouseroom> wareHouseWrapper = meituanDataProcessUtil.processWareHouse(mtWhoutitem.getMtWhCode(),mtShop,salesspecification);
        if(!wareHouseWrapper.isSuccess()){
            mtWhout.setRemark(wareHouseWrapper.getMessage());
            mtWhoutitem.setRemark(wareHouseWrapper.getMessage());
            mtWhout.setStatus(10);
            return false;
        }
        Storehouseroom storehouseroom = wareHouseWrapper.getTarget();
        Storeroom storeroom = meituanDataProcessUtil.storeroomMap.get(mtWhoutitem.getMtWhCode());
        mtWhoutitem.setStoreroomguid(storeroom.getGuid());
        mtWhoutitem.setStoreroomname(storeroom.getName());
        mtWhoutitem.setStorehouseguid(storehouseroom.getGuid());
        mtWhoutitem.setStorehousename(storehouseroom.getName());

        //库存单位
        ProcessWrapper<Stockunit> stockunitProcessWrapper = meituanDataProcessUtil.processStockUnit(salesspecification.getStockunitid());
        if(!stockunitProcessWrapper.isSuccess()){
            mtWhout.setRemark(stockunitProcessWrapper.getMessage());
            mtWhoutitem.setRemark(stockunitProcessWrapper.getMessage());
            mtWhout.setStatus(10);
            return false;
        }
        Stockunit stockunit = stockunitProcessWrapper.getTarget();
        mtWhoutitem.setStockunitid(stockunit.getId());
        mtWhoutitem.setStockunitname(stockunit.getUnitName());
        //物料设置了转换率，不再需要通过两个单位比较获取转换率
//        Stockunit mtStockunit = stockunitService.selectStockunitById(salesspecification.getMtStockunitId());
//        if(mtStockunit==null){
//            mtWhout.setRemark("物料的美团库存单位设置不正确");
//            mtWhoutitem.setRemark("物料的美团库存单位设置不正确");
//            mtWhout.setStatus(10);
//            return false;
//        }
        //处理数量及单价
        BigDecimal rate = salesspecification.getMttostockUnitRate();
        if(rate==null || rate.compareTo(BigDecimal.ZERO)==0){
            mtWhout.setRemark("物料的美团单位转换率设置错误！");
            mtWhoutitem.setRemark("物料的美团单位转换率设置错误！");
            mtWhout.setStatus(10);
        }
        mtWhoutitem.setErpWeight(mtWhoutitem.getAmount().multiply(rate));
        mtWhoutitem.setErpPrice(mtWhoutitem.getPrice().divide(rate));
        mtWhoutitem.setRemark("待同步");
        return true;
    }

    /**
     * 库组织交易处理，找到内部机构对应的客户信息
     * @param mtWhout     美团出库单主表数据
     * @param mtShop      美团店铺
     * @return
     */
    private boolean diffOrgProcess(MtWhout mtWhout, MtShop mtShop) {

        //调拨出库库、配送出库，可能需要处理跨组织的内部结算，其他类型出库单不需要处理
        if(!MeituanDataProcessUtil.whoutDiffOrgMap.keySet().contains(mtWhout.getType())){
            return true;
        }

        //TODO 判断同组织还是跨组织，暂时不知道怎么判断
        boolean sameOrg = true;

        //判断跨组织交易逻辑
        Organization organization=null;  //出库交易的对方组织
        if(mtWhout.getOppositeorgType().intValue()==2){
            //对方机构类型如果是内部机构
            ProcessWrapper<Organization> orgProcessWrapper = meituanDataProcessUtil.getOrgByMtcode(mtWhout.getOppositeorgCode());
            if(!orgProcessWrapper.isSuccess()){
                mtWhout.setStatus(10);
                mtWhout.setRemark(orgProcessWrapper.getMessage());
                return false;
            }
            organization = orgProcessWrapper.getTarget();
            sameOrg = organization.getId().equals(mtWhout.getOrgId());
        } else {
            //入库交易的对方组织不是内部组织
            mtWhout.setStatus(10);
            mtWhout.setRemark("配送/调拨出库单的对方组织不是内部机构！");
            return false;
        }

        if(sameOrg){
            //同组织的，直接返回，不需要处理了
            return true;
        }

        //跨组织，需要重新确定出库类型
        mtWhout.setErpType(meituanDataProcessUtil.getWhoutErpTypeByMtType(true, mtWhout.getType()));
        if(mtWhout.getErpType()==null){
            mtWhout.setStatus(10);
            mtWhout.setRemark("入库单类型匹配错误");
            return false;
        }

        ProcessWrapper<Customer> customerProcessWrapper = meituanDataProcessUtil.findCustomerOrg(organization);
        if(!customerProcessWrapper.isSuccess()){
            mtWhout.setStatus(10);
            mtWhout.setRemark(customerProcessWrapper.getMessage());
            return false;
        }
        Customer customer = customerProcessWrapper.getTarget();
        mtWhout.setCustomerguid(customer.getGuid());
        mtWhout.setCustomername(customer.getName());
        return true;
    }

}
